<template>
  <div class="password-change-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>修改密码</h1>
      <p>请设置您的新密码，确保账户安全</p>
    </div>

    <!-- 密码修改表单 -->
    <el-card class="password-form-card" shadow="hover">
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="rules"
        label-width="120px"
        class="password-form"
      >
        <!-- 卡号 -->
        <el-form-item label="卡号" prop="cardNumber">
          <el-input
            v-model="passwordForm.cardNumber"
            placeholder="请输入卡号"
          ></el-input>
        </el-form-item>

        <!-- 当前密码 -->
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          ></el-input>
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
            @input="checkPasswordStrength"
          ></el-input>
          <!-- 密码强度指示器 -->
          <div class="password-strength" v-if="passwordStrength !== null">
            <div
              class="strength-bar"
              :class="[
                passwordStrength === 1 ? 'bg-red' : '',
                passwordStrength === 2 ? 'bg-yellow' : '',
                passwordStrength === 3 ? 'bg-green' : '',
              ]"
              :style="{ width: `${passwordStrength * 33.33}%` }"
            ></div>
            <div class="strength-text">
              {{
                passwordStrength === 1
                  ? "弱"
                  : passwordStrength === 2
                  ? "中"
                  : "强"
              }}
            </div>
          </div>
        </el-form-item>

        <!-- 确认新密码 -->
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          ></el-input>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">确认修改</el-button>
          <el-button @click="handleReset" plain>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";

const passwordFormRef = ref(null);
const passwordForm = reactive({
  cardNumber: "",
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 密码强度 (0: 无, 1: 弱, 2: 中, 3: 强)
const passwordStrength = ref(null);

// 表单校验规则
const rules = {
  cardNumber: [{ required: true, message: "请输入卡号", trigger: "blur" }],
  oldPassword: [
    { required: true, message: "请输入当前密码", trigger: "blur" },
    { min: 6, max: 6, message: "密码长度必须为6位", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (/[a-zA-Z]/.test(value)) {
          callback(new Error("密码不能包含字母"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 6, message: "密码长度必须为6位", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (/[a-zA-Z]/.test(value)) {
          callback(new Error("密码不能包含字母"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 检查密码强度
const checkPasswordStrength = (value) => {
  if (!value) {
    passwordStrength.value = null;
    return;
  }

  let strength = 0;

  // 长度检查
  if (value.length === 6) strength++;

  // 不包含字母
  if (!/[a-zA-Z]/.test(value)) strength++;

  // 包含数字
  if (/\d/.test(value)) strength++;

  // 计算最终强度 (0-3)
  passwordStrength.value = Math.min(strength, 3);
};

// 提交表单
const handleSubmit = async () => {
  try {
    await passwordFormRef.value.validate();

    // 构建请求参数
    const params = new URLSearchParams();
    params.append("cardid", passwordForm.cardNumber);
    params.append("pass", passwordForm.newPassword);

    // 发送请求到后端
    const response = await axios.put(
      "http://localhost:8088/api/cards/updatepassparam",
      params
    );

    // 处理后端响应
    if (response.data.success) {
      ElMessage.success("密码修改成功，可以使用新密码登录");
      handleReset();
    } else {
      ElMessage.error("密码修改失败，请重试");
    }
  } catch (error) {
    ElMessage.error("请求失败，请检查您的网络连接");
    console.error("Error:", error);
  }
};

// 重置表单
const handleReset = () => {
  passwordFormRef.value.resetFields();
  passwordStrength.value = null;
};
</script>

<style scoped>
/* 容器样式 */
.password-change-container {
  max-width: 600px;
  margin: 40px auto;
  padding: 0 20px;
}

/* 页面标题 */
.page-header {
  text-align: center;
  margin-bottom: 30px;
}
.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #333;
}
.page-header p {
  font-size: 14px;
  color: #999;
}

/* 表单卡片 */
.password-form-card {
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 表单间距 */
.password-form :deep(.el-form-item) {
  margin-bottom: 25px;
}

/* 密码强度指示器 */
.password-strength {
  margin-top: 8px;
}
.strength-bar {
  height: 4px;
  border-radius: 2px;
  transition: width 0.3s ease;
}
.bg-red {
  background-color: #f56c6c;
}
.bg-yellow {
  background-color: #e6a23c;
}
.bg-green {
  background-color: #67c23a;
}
.strength-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: center;
}

/* 按钮间距 */
.password-form :deep(.el-button) {
  margin-right: 10px;
}
</style>
